// miniprogram/pages/order/add.js
import * as R from 'ramda';
import { Reader } from '../../utils/vendor/ramda-fantasy';
import U from '../../utils/index';
import WxValidate from '../../utils/vendor/WxValidate.js';
import dayjs from 'dayjs';
import config from '../../config/index'
import Dialog from "../../miniprogram_npm/vant-weapp/dialog/dialog"
const validator = {
  rules: {
    order_type: {
      required: true,
    },
    realname: {
      required: true,
    },
    card_num: {
      required: true,
    },
    mobile: {
      required: true,
    },
    address: {
      required: true,
    },
    device_model: {
      required: true,
    },
    rent_start_date: {
      required: true,
    },
    rent_end_date: {
      required: true,
    },
    install_date: {
      required: true,
    },
    change_date: {
      required: true,
    },
    daily_amount: {
      required: true,
    },
    first_amount: {
      required: true,
    },
    sell_user_id: {
      required: true,
    },
    after_user_id: {
      required: true,
    },
  },
  messages: {
    order_type: {
      required: '请选择订单类型',
    },
    realname: {
      required: '请输入客户姓名',
    },
    card_num: {
      required: '请输入客户身份证',
    },
    mobile: {
      required: '请输入客户客户手机',
    },
    address: {
      required: '请输入安装地址',
    },
    device_model: {
      required: '请输入设备型号',
    },
   rent_start_date: {
      required: '请选择租赁期限开始日期',
    },
    rent_end_date: {
      required: '请选择租赁期限结束日期',
    },
    install_date: {
      required: '请选择设备安装时间',
    },
    change_date: {
      required: '请选择滤芯更换时间',
    },
    daily_amount: {
      required: '请输入每日租金',
    },
    first_amount: {
      required: '请输入初装费用',
    },
    sell_user_id: {
      required: '请选择销售人员',
    },
    after_user_id: {
      required: '请选择售后人员',
    },
  }
};
const wxValidateCreate = new WxValidate(validator.rules, validator.messages);
const changeValidatorUpdate = R.map(R.omit([ 'rent_start_date', 'rent_end_date', 'install_date', 'change_date' ]));
const wxValidateUpdate = new WxValidate(changeValidatorUpdate(validator).rules, changeValidatorUpdate(validator).messages);

const requestSearchUser = data => U.reqPost({
  url:'/user/user_list',
  data
});

const requestAllSearchUser = () => U.handleRequest({}, () => Promise.all([
  requestSearchUser({ role_type: 1 }),
  requestSearchUser({ role_type: 2 }),
]));

const handleUser = R.compose(R.map(R.pick(['user_id', 'realname'])), R.path(['data', 'list']));

const handleRequestCreateForm = U.reqPostShow('/order/add_order', '新增订单成功！');
const handleRequestUpdateForm = U.reqPostShow('/order/update', '修改订单成功！');
const handleRequestDel = U.reqPostShow('/order/delete_info', '删除订单成功！');

// 日期不为空就转化为时间戳
/* const changeTimeStamp = R.unless(R.isNil, date => dayjs(date).toDate().getTime()); */
// 转化成时间戳存放到aliasForm里
/* const setAliasFormDate = dateNames => data => Reader(that => {
  R.map(
    dateName => that.setData({
      ['aliasForm.' + dateName]: changeTimeStamp(data[dateName])
    })
  )(dateNames);
  return data;
}); */
//  处理上一页面返回的订单数据
const handleGetFormData = R.compose(
  R.chain(data => Reader(that => {
    that.setData({ form: data })
    return data;
  })),
  R.map(R.pick(['order_type', 'realname', 'card_num', 'mobile', 'address', 'emerge_person_name', 'emerge_person_mobile', 'device_model', /*'rent_start_date', 'rent_end_date', 'install_date', 'change_date', */'daily_amount', 'first_amount', 'sell_user_id', 'after_user_id',  'remark'])),
  data => Reader(that => {
    that.setData({
      ['aliasForm.orderTypeName']: that.data.pickerData.orderTypes[data.order_type],
      ['aliasForm.salesName']: data.sell_user.realname,
      ['aliasForm.salesAfterName']: data.after_user.realname,
    })
    return data;
  })
  // setAliasFormDate([ 'rent_start_date', 'rent_end_date', 'install_date', 'change_date' ])
)

Page({

  /**
   * 页面的初始数据
   */
  data: {
    isShowPage: false,
    form: {},
    aliasForm: {},
    pickerData: {
      isShowOrderType: false,
      orderTypes: config.orderTypes,
      isShowSales: false,
      sales: null,
      isShowSalesAfter: false,
      salesAfter: null,
    },
    datePickerData: {
      isShowRentStartDate: false,
      isShowRentEndDate: false,
      isShowInstallDate: false,
      isShowChangeDate: false,
    },
    currentDate: new Date().getTime(),
    maxDate: dayjs().add(10, 'year').toDate().getTime(),
    minDate: dayjs().subtract(10, 'year').toDate().getTime(),
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    R.compose(
      U.fork,
      R.map(
        R.compose(
          R.unless(
            () => R.isNil(options.orderId),
            () => {
              handleGetFormData(U.getPrevPage().data.pageData).run(this);
              this.setData({ ['form.order_id']: Number(options.orderId) });
              wx.setNavigationBarTitle({ title: '修改订单' })
              return
            }
          ),
          results => this.setData({
            ['pickerData.sales']: handleUser(results[0]),
            ['pickerData.salesAfter']: handleUser(results[1]),
            isShowPage: true,
          }),
        )
      ),
      requestAllSearchUser
    )()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  
  onSubmit() {
    R.compose(
      U.runIO,
      U.handleError,
      R.map(
        R.compose(
          U.fork,
          R.map(
            R.compose(
              U.runIO,
              U.backReqSuc,
            )
          ),
          R.ifElse(
            () => R.isNil(this.data.form.order_id),
            handleRequestCreateForm,
            handleRequestUpdateForm
          )
        )
      ),
      R.ifElse(
        () => R.isNil(this.data.form.order_id),
        U.validate(wxValidateCreate),
        U.validate(wxValidateUpdate),
      ),
      R.tap(form => this.setData({ form })),
      R.map(U.trim),
    )(this.data.form);
  },
  onClickDel() {
    R.composeP(
      R.compose(
        U.fork,
        R.map(
          () => setTimeout(() => wx.reLaunch({ url: '/pages/order/index' }), 1500)
        ),
        () => handleRequestDel({ order_id: this.data.form.order_id }),
      ),
      () => Dialog.confirm({ message: '是否确认删除该订单？' })
    )();
  },
  setFormData(e) {
    U.setFormData(e).run(this);
  },
  // 订单类型下拉
  switchOrderTypePicker() {
    this.setData({
      ['pickerData.isShowOrderType']: !this.data.pickerData.isShowOrderType,
    });
  },
  // 订单类型确定
  onConfirmOrderTypePicker(e) {
    this.setData({
      [ 'form.order_type' ]: e.detail.index,
      [ 'aliasForm.orderTypeName' ]: e.detail.value,
      [ 'pickerData.isShowOrderType' ]: false,
    })
  },
  // 销售下拉显示切换
  switchSalesPicker() {
    this.setData({
      ['pickerData.isShowSales']: !this.data.pickerData.isShowSales,
    });
  },
  // 销售确定
  onConfirmSalesPicker(e) {
    this.setData({
      [ 'form.sell_user_id' ]: e.detail.value.user_id,
      [ 'aliasForm.salesName' ]: e.detail.value.realname,
      [ 'pickerData.isShowSales' ]: false,
    })
  },
  // 售后下拉显示切换
  switchSalesAfterPicker() {
    this.setData({
      ['pickerData.isShowSalesAfter']: !this.data.pickerData.isShowSalesAfter,
    });
  },
  // 售后确定
  onConfirmSalesAfterPicker(e) {
    this.setData({
      [ 'form.after_user_id' ]: e.detail.value.user_id,
      [ 'aliasForm.salesAfterName' ]: e.detail.value.realname,
      [ 'pickerData.isShowSalesAfter' ]: false,
    })
  },
  switchRentStart() {
    this.setData({
      [ 'datePickerData.isShowRentStartDate' ]: !this.data.datePickerData.isShowRentStartDate,
    })
  },
  onConfirmRentStart(e) {
    this.setData({
      [ 'form.rent_start_date' ]: dayjs(e.detail).format('YYYY-MM-DD'),
      [ 'aliasForm.rent_start_date' ]: e.detail,
      [ 'datePickerData.isShowRentStartDate' ]: false,
      // 设置滤芯更换时间
      [ 'form.change_date' ]: dayjs(e.detail).add(6, 'month').format('YYYY-MM-DD'),
      [ 'aliasForm.change_date' ]: dayjs(e.detail).add(6, 'month').toDate().getTime(),
    })
  },
  switchRentEnd() {
    this.setData({
      [ 'datePickerData.isShowRentEndDate' ]: !this.data.datePickerData.isShowRentEndDate,
    })
  },
  onConfirmRentEnd(e) {
    this.setData({
      [ 'form.rent_end_date' ]: dayjs(e.detail).format('YYYY-MM-DD'),
      [ 'aliasForm.rent_end_date' ]: e.detail,
      [ 'datePickerData.isShowRentEndDate' ]: false,
    })
  },
  switchInstallDate() {
    this.setData({
      [ 'datePickerData.isShowInstallDate' ]: !this.data.datePickerData.isShowInstallDate,
    })
  },
  onConfirmInstallDate(e) {
    this.setData({
      [ 'form.install_date' ]: dayjs(e.detail).format('YYYY-MM-DD'),
      [ 'aliasForm.install_date' ]: e.detail,
      [ 'datePickerData.isShowInstallDate' ]: false,
    })
  },
  switchChangeDate(e) {
    this.setData({
      [ 'datePickerData.isShowChangeDate' ]: !this.data.datePickerData.isShowChangeDate,
    })
  },
  onConfirmChangeDate(e) {
    this.setData({
      [ 'form.change_date' ]: dayjs(e.detail).format('YYYY-MM-DD'),
      [ 'aliasForm.change_date' ]: e.detail,
      [ 'datePickerData.isShowChangeDate' ]: false,
    })
  },
});
